package com.base.log;

import com.alibaba.fastjson.JSONObject;
import com.base.exception.ModelAndViewRuntimeException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@SuppressWarnings("unchecked")
public class RequestUtils {

    private final RedisTemplate<String, Object> redisTemplate;

    private final static String dir = "WEB_USER_INFO:";

    public RequestUtils(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public Map<String, Object> getUserData(){
        HttpServletRequest httpServletRequest = RequestHolder.getHttpServletRequest();
        String id = httpServletRequest.getSession().getId();
        Map<String, Object> userMap;
        try {
            Object s = redisTemplate.opsForValue().get(dir + id);
            userMap = JSONObject.parseObject(String.valueOf(s));
            if (userMap == null) {
                redisTemplate.delete(dir + id);
                throw new ModelAndViewRuntimeException("redirect:/admin/loginCheck1");
            }
        }catch (Exception e) {
            e.printStackTrace();
            redisTemplate.delete(dir + id);
            throw new ModelAndViewRuntimeException("redirect:/admin/loginCheck1");
        }
        return userMap;
    }
}
